package com.netscenery.util;

import java.util.ArrayList;

public class Field{
	private ArrayList<String> fields;
	
	public Field(String fields){
		String[] fieldsEx = fields.split(" ");
		int length = fieldsEx.length;
		for (int i = 0; i< length;i++){
			String field = fieldsEx[i];
			if (null != field){
				field = field.trim();
				if (null != field && (field.length() != 0)){
					addField(field);
				}
			}
		}
	}

	public boolean addField(String field){
		if (null == field){
			return false;
		}
		
		if (null == fields){
			fields = new ArrayList<String> (1);
		}
		if (hasField(field)){
			return false;
		}

		
		if (false == fields.add(field)){
			return false;
		}
		
		
		return true;
	}
	
	public boolean hasField(String name){
		if (null == name){
			return false;
		}
		if (null == fields){
			return false;
		}
		
		int size = fields.size();
		
		for (int i = 0; i < size; i++){
			String f = fields.get(i);
			if (null != f){
				if (f.equals(name)){
					return true;
				}
			}
		}
		
		return false;
	}
	public int getFieldsNumber(){
		if (null == fields){
			return 0;
		}
		
		return fields.size();
	}
	public String getField(int index){
		if (null == fields){
			return null;
		}
		
		return fields.get(index);
	}
	
	public String removeField(int index){
		if (null == fields){
			return null;
		}
		
		return fields.remove(index);
	}
	public String removeField(String name){
		if (null == fields){
			return null;
		}
		
		int size = fields.size();
		
		for (int i = 0; i < size; i++){
			String node = fields.get(i);
			if (null != node){
				if (node.equals(name)){
					return fields.remove(i);
				}
			}
		}
		
		return null;
	}
	

	public String toString(){
		if (0 == getFieldsNumber()){
			return null;
		}
		int size = getFieldsNumber();
		StringBuffer sb = null;
		for (int i = 0; i < size; i++){
			String f = getField(i);
			if (null == f){
				continue;
			}
			if (null == sb){
				sb = new StringBuffer();
			}
			else {
				sb.append(" ");
			}
			sb.append(f);
		}
		if (null != sb){
			return sb.toString();
		}
		
		return null;
	}
}
